package com.lh.web.interceptor;

import java.net.URLEncoder;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.lh.annotation.UserType;
import com.lh.annotation.UserType.Type;
import com.lh.biz.IUserBiz;
import com.lh.cache.CacheManager;
import com.lh.entity.User;
import com.lh.util.HttpUtil;
import com.lh.util.SessionUtil;

/**
 * @author liuhui
 * @version 1.0
 * @date 2013-4-5 下午12:42:26
 */
public class SessionTokenInterceptor extends HandlerInterceptorAdapter {
	
	public static final String 	LOGIN_URL = "http://www.kaijingbao.com/user/login" ;
	
	@Resource
	private CacheManager cacheManager;
	
	@Override
	public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
		if(!(handler instanceof HandlerMethod)){
			return super.preHandle(request, response, handler);
		}
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		UserType userType= handlerMethod.getMethodAnnotation(UserType.class);
		if (null == userType) {
			userType = handlerMethod.getBeanType().getAnnotation(UserType.class);
		}
		
		String sessionToken = getSessionToken(request);
		
		User u = (User) cacheManager.getValue(sessionToken);
		if(u == null && (userType != null && !hasType(userType , UserType.Type.ANONYMOUS))){
			
			boolean isAjax = HttpUtil.isAjax(request);
			if (isAjax) {
				response.setContentType("application/json;charset=UTF-8");
				JSONObject json = new JSONObject();
				json.put("noLogin", true);
				json.put("message", "登录超时");
				response.getWriter().print(json.toString());
				return false;
			}
			
			
			String redirectUrl =   request.getRequestURL().toString();
			if(request.getQueryString() != null ){
				redirectUrl += ("?" + request.getQueryString());
			}
			response.sendRedirect(LOGIN_URL+"?redirectUrl=" + URLEncoder.encode( redirectUrl  , "utf-8"));
			return false;
		}
		
		if(u != null ){
			SessionUtil.setUser(u);
			cacheManager.setValue(sessionToken,u, IUserBiz.LOGIN_TIME_OUT);
		}else{
			SessionUtil.setUser(null);
		}
		
		return super.preHandle(request, response, handler);
	}

	private boolean hasType(UserType userType, Type anonymous) {
		if(userType != null ){
			for (Type t : userType.value()) {
				if(t.equals(anonymous)){
					return true;
				}
			}
		}
		return false;
	}

	private String getSessionToken(HttpServletRequest request) {
		String sessionToken = request.getParameter(IUserBiz.SESSION_TOKEN_NAME);
		if(sessionToken == null ){
			if(request.getCookies() != null ){
				for (Cookie cookie : request.getCookies()) {
					if(IUserBiz.SESSION_TOKEN_NAME.equals(cookie.getName())){
						sessionToken = cookie.getValue();
						break;
					}
				}
			}
			
		}
		return sessionToken;
	}
}
